package cn.leedsoft.luma.controller;

import cn.leedsoft.luma.common.Reply;
import cn.leedsoft.luma.controller.vo.UserVo;
import cn.leedsoft.luma.mapper.domain.User;
import cn.leedsoft.luma.service.dto.T1;
import cn.leedsoft.luma.web_service.OssClientHelper;
import com.alibaba.fastjson.JSON;
import com.google.common.collect.Maps;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.core.io.Resource;
import org.springframework.format.datetime.DateFormatter;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.context.support.ServletContextResource;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.commons.CommonsMultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.*;
import java.net.URLEncoder;
import java.util.*;

/**
 * Created by leeds on 2016/6/28 10:56.
 */
@Controller
@RequestMapping("/test")
public class TestController {
    //返回view
    @RequestMapping(value = {"/", ""})
    public ModelAndView get(HttpServletRequest request) {
        ModelAndView modelAndView = new ModelAndView("/test");
        modelAndView.addObject("leeds", "jung");
        modelAndView.addObject("T", new T1());
        return modelAndView;
    }

    //返回json
    @RequestMapping(value = "/to_ajax")
    @ResponseBody
    public Object toAjax(HttpServletRequest request) {
        Map<String, Object> res = Maps.newHashMap();
        res.put("leeds", "soft");
        res.put("wc", "王聪");
        res.put("nih", null);
        res.put("digit", 1);

//        return res;
        User user = new User();
        user.setNickname("里子");
        user.setUserUuid("dlfjslkfjsl");
        user.setCreateTime(new Date());//自动转为时间戳

        System.out.println(request.getHeader("Referer").contains("test"));
        return user;
    }
    //上传文件
    @RequestMapping(value = "/upload_file")
    @ResponseBody
    public Map<String, Object> uploadFile(String name, MultipartFile file, HttpServletRequest request) {
//        File dest = new File("/test/" + file.getOriginalFilename());
        Resource resource = new ServletContextResource(request.getServletContext(), "/WEB-INF/" + file.getOriginalFilename());
        try {
//            file.transferTo(resource.getFile());
            System.out.println(file.getContentType());
            System.out.println(file.getOriginalFilename());
            new OssClientHelper().putMultipartFile(file, "userfiles/1/images/201604");
        } catch (IOException e) {
            e.printStackTrace();
        }

        Map<String, Object> res = Maps.newHashMap();
        res.put("leeds", "soft");
        return res;
    }
    //下载文件//note：urlencode部分
    @RequestMapping(value = "/download_file")
    public void downloadFile(HttpServletRequest request, HttpServletResponse response) {
        byte[] buf = new byte[1024*20];//写代码，要分块，分模块，编写。以使逻辑有条理
        BufferedInputStream bufferedInputStream = null;
        BufferedOutputStream bufferedOutputStream = null;
        int readOnceNumber;

        try {
            Resource resource = new ServletContextResource(request.getServletContext(), "/WEB-INF/360截图20160603091823545.jpg");
            bufferedInputStream = new BufferedInputStream(resource.getInputStream());

            response.setContentType("image/jpeg");//对于response一个文本文件、json来说，设置Charset，是必要的。
            try {
                response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode("360截图.jpg", "utf-8"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            bufferedOutputStream = new BufferedOutputStream(response.getOutputStream());
            while ((readOnceNumber = bufferedInputStream.read(buf)) != -1) {
                bufferedOutputStream.write(buf, 0, readOnceNumber);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                bufferedInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                bufferedOutputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    /**
     * 1、@ResponseBody 通常用于ajax，返回json。要求返回固定格式的json。所以return-type要求是Reply
     * 2、要对http参数进行验证，需要将handler method声明为XXValid， 同时对相应vo添加@Valid，并且紧随其后要求必须有一个BindingResult参数，用于接收验证结果
     *      因为已经写了一个controller-aop用于拦截验证结果了，所以，一般controller不必再进行验证。
     */
    @RequestMapping("/valid_parameters/{path}")
    @ResponseBody
    public Reply validParametersValid(String str, @RequestParam("intVal")Integer i, Date date, String[] ids,
                                               /*User user,*/ @Valid UserVo userVo,BindingResult bindingResult, @PathVariable String path) {
        Map<String, Object> res = Maps.newHashMap();
        res.put("str", str);
        res.put("intVal", i);
        res.put("path", path);
        res.put("date", new DateFormatter("yyyy-MM-dd HH:mm:ss").print(date, Locale.CHINESE));
//        res.put("user", JSON.toJSONString(user));
        //所有基本类型，使用包装类，是为了，通过null判断，是否传递了该参数。
        res.put("我", "d你");
        return Reply.success(res);
    }

    @RequestMapping("testAjaxForm")
    @ResponseBody
    public Reply testAjaxForm(HttpServletRequest request, @RequestParam("files") MultipartFile[] files) {//!!important::@RequestParam("files")
//        DiskFileItemFactory fileItemFactory = new DiskFileItemFactory();
//        ServletFileUpload uploadHandler = new ServletFileUpload(
//                fileItemFactory);
//
//        try {
//            List<FileItem> items = uploadHandler.parseRequest(request);
//            Iterator<FileItem> itr = items.iterator();
//            while (itr.hasNext()) {
//                FileItem item = (FileItem) itr.next();
//                System.out.println("-------------");
//            }
//            System.out.println(JSON.toJSONString(items));
//            System.out.println(request.getParameterMap());
//        } catch (FileUploadException e) {
//            e.printStackTrace();
//        }

        if (files != null) {
            for (MultipartFile file : files) {
                try {
                    Resource resource = new ServletContextResource(request.getServletContext(), "/WEB-INF/" + file.getOriginalFilename());
                    file.transferTo(resource.getFile());
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
//        try {
//            Resource resource = new ServletContextResource(request.getServletContext(), "/WEB-INF/" + files.getOriginalFilename());
//            files.transferTo(resource.getFile());
//        } catch (IOException e) {
//            e.printStackTrace();
//        }

//        return Reply.success("成功上传文件" + files.getContentType() + files.getName() + files.getOriginalFilename());
        return Reply.success("成功上传文件");
    }
}
